package com.hnzq.cloud.freshaddressassembly.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hnzq.cloud.GoodsOrderAPI;
import com.hnzq.cloud.OrderAPI;
import com.hnzq.cloud.api.BalanceApi;
import com.hnzq.cloud.api.FreGoodsAPI;
import com.hnzq.cloud.balanceParam.AddBalanceParam;
import com.hnzq.cloud.balanceParam.CountBalanceParam;
import com.hnzq.cloud.balanceParam.FindBalanceParam;
import com.hnzq.cloud.balanceParam.UpdateBalanceParam;
import com.hnzq.cloud.dto.*;
import com.hnzq.cloud.freshaddressassembly.domain.FreBalance;
import com.hnzq.cloud.freshaddressassembly.domain.FreSite;
import com.hnzq.cloud.freshaddressassembly.domain.FreSiteBalance;
import com.hnzq.cloud.freshaddressassembly.service.IFreBalanceService;
import com.hnzq.cloud.freshaddressassembly.service.impl.FreSiteBalanceServiceImpl;
import com.hnzq.cloud.freshaddressassembly.service.impl.FreSiteServiceImpl;
import com.hnzq.cloud.freshaddressassembly.util.WoniuBeanUtils;
import com.hnzq.cloud.model.Result;
import com.hnzq.cloud.param.FindOrderBySiteIdParam;
import com.hnzq.cloud.siteBalanceParam.OneSiteBalanceParam;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author qinle
 * @since 2022-02-10
 */
@RestController
@RequestMapping("/freBalance")
public class FreBalanceController implements BalanceApi {
    @Resource
    private IFreBalanceService freBalanceService;
    @Resource
    private FreGoodsAPI freGoodsAPI;
    @Resource
    private OrderAPI orderAPI;
    @Resource
    private GoodsOrderAPI goodsOrderAPI;
    //新增佣金表


    @Override
    public Result addBalance(AddBalanceParam addBalanceParam) {
        FindOrderBySiteIdParam findOrderBySiteIdParam = WoniuBeanUtils.copyObject(addBalanceParam, FindOrderBySiteIdParam.class);
        PageOrdersDto pageOrdersDto = (orderAPI.findOrderBySiteId(findOrderBySiteIdParam)).getData();

//        System.out.println(pageOrdersDto);
        List<OrderDto> orderDtoList = pageOrdersDto.getOrderDtoList();

        for(int i=0;i<orderDtoList.size();i++){
            //获取订单id
            Integer orderId = orderDtoList.get(i).getOrderId();

            List<FreGoodsOrder> freGoodsOrders = goodsOrderAPI.findGoodsOrderByOrderId(orderId).getData();
            //订单详情
//            List<FreGoodsOrder> freGoodsOrders = mapper.convertValue(data1, new TypeReference<List<FreGoodsOrder>>() {
//            });
            //
            List<Integer> ids = freGoodsOrders.stream().map(item -> item.getGoodsId()).collect(Collectors.toList());
            Map<Integer, FreGoodsDto> goodsDtoMap = freGoodsAPI.findGoodsInfos(ids).getData();
            BigDecimal bigDecimal = new BigDecimal(0);
            for (int a=0;a<freGoodsOrders.size();a++){
                FreGoodsDto freGoodsDto = goodsDtoMap.get(ids.get(a));
                //商品单价
                BigDecimal goodsPrice = freGoodsDto.getGoodsPrice();
                //佣金比例
                BigDecimal balanceconfPercent = freGoodsDto.getBalanceconfPercent();
                //商品数量
                Integer goodsCount = freGoodsOrders.get(a).getGoodsCount();
                BigDecimal goodsCount1 = BigDecimal.valueOf(goodsCount);
                //单个商品的佣金
                BigDecimal money = balanceconfPercent.multiply(goodsPrice).multiply(goodsCount1);
                bigDecimal= bigDecimal.add(money);
            }
            FreBalance freBalance = new FreBalance();
            System.out.println(orderDtoList.get(i));
            freBalance.setBalanceCreatetime(orderDtoList.get(i).getRawAddTime());
            freBalance.setBalanceMoney(bigDecimal);
            //0表示未结算
            freBalance.setBalanceStatus(0);
            freBalance.setOrderId(orderId);
            freBalance.setSiteId(addBalanceParam.getSiteId());
             freBalanceService.save(freBalance);
            return Result.newInstance().setMessage("新增门店佣金信息成功").setData(freBalance);

        }

        return Result.newInstance().setMessage("新增门店佣金信息失败");
    }
   //根据时间和门店id查询佣金总额和详情

    @Override
    public Result<FindBalanceBySiteIdDto> findBalanceBySiteId(FindBalanceParam findBalanceParam) {
        List<FreBalance> freBalanceList = freBalanceService.list(new QueryWrapper<FreBalance>().eq("site_id", findBalanceParam.getSiteId()).eq("balance_createtime", findBalanceParam.getBalanceCreatetime()));
        BigDecimal bigDecimal = new BigDecimal(0);
        for(int i=0;i<freBalanceList.size();i++){
            bigDecimal.add(freBalanceList.get(i).getBalanceMoney());
        }
        FindBalanceBySiteIdDto findBalanceBySiteIdDto = new FindBalanceBySiteIdDto();
        findBalanceBySiteIdDto.setAllMoney(bigDecimal);
        findBalanceBySiteIdDto.setListBalance(WoniuBeanUtils.copyList(freBalanceList, OneBalanceDto.class));
        return Result.newInstance().setMessage("查询佣金成功").setData(findBalanceBySiteIdDto);
    }
    @Resource
    private FreSiteServiceImpl freSiteService;
    @Resource
    private FreSiteBalanceServiceImpl freSiteBalanceService;
    //月结算店长佣金
    @GlobalTransactional
    @Override
    public Result<String> countBalanceBySiteId(CountBalanceParam countBalanceParam) {

        //1：查询所有门店的id
        //2：对每个id执行你下面的
        //大于开始时间，小于结束时间，状态时已结算(所有的)
        List<FreBalance> freBalanceList = freBalanceService.list(new QueryWrapper<FreBalance>()
                .eq("balance_status",3));
//                .ge("balance_createtime",countBalanceParam.getStartTime())
//                .le("balance_createtime",countBalanceParam.getEndTime()));
//                .apply("UNIX_TIMESTAMP(balance_createtime) <= UNIX_TIMESTAMP('"+countBalanceParam.getStartTime()+"')")
//                .apply("UNIX_TIMESTAMP(balance_createtime) >= UNIX_TIMESTAMP('"+countBalanceParam.getEndTime()+"')"));



        System.out.println(freBalanceList);

        //所有没有被删除的site
        List<FreSite> siteList = freSiteService.list(new QueryWrapper<FreSite>().eq("is_delete", 0));
        //所有的门店Id的
        List<Integer> SiteIds = siteList.stream().map(item -> item.getSiteId()).collect(Collectors.toList());

        Map<Integer, BigDecimal> money = new HashMap<>();


        for (int i=0;i<SiteIds.size();i++){
            money.put(SiteIds.get(i),new BigDecimal(0));
            for (FreBalance freBalance : freBalanceList) {
                   if (freBalance.getSiteId()==SiteIds.get(i)){
                       BigDecimal bigDecimal = money.get(SiteIds.get(i));
                       bigDecimal=bigDecimal.add(freBalance.getBalanceMoney());
                       money.put(SiteIds.get(i),bigDecimal);
                   }
            }
        }


        for (int a=0;a<freBalanceList.size();a++){
            //改变状态为已结算
            freBalanceList.get(a).setBalanceStatus(1);
        }
         freBalanceService.updateBatchById(freBalanceList);
        //获取map的keys
        Set<Integer> integers = money.keySet();
       // ListSiteBalanceParam listSiteBalanceParam = new ListSiteBalanceParam();
        List<OneSiteBalanceParam> listSiteBalance = new ArrayList<>();

        for (Integer integer : integers) {
            OneSiteBalanceParam oneSiteBalance = new OneSiteBalanceParam();
            oneSiteBalance.setSiteId(integer);
            oneSiteBalance.setCountBalance(money.get(integer));
            oneSiteBalance.setLogoTime(countBalanceParam.getEndTime());
            listSiteBalance.add(oneSiteBalance);
        }


        if (freSiteBalanceService.saveBatch(WoniuBeanUtils.copyList(listSiteBalance, FreSiteBalance.class))) {
            return Result.newInstance().setMessage("计算佣金成功").setData(listSiteBalance);
        }
        return Result.newInstance().setMessage("计算佣金失败");


    }
    //退货减相应佣金
    @Override
    public Result updateBalance(UpdateBalanceParam updateBalanceParam) {
        FreBalance freBalance = freBalanceService.getOne(new QueryWrapper<FreBalance>().eq("order_id", updateBalanceParam.getOrderId()));
        BigDecimal oldMoney = freBalance.getBalanceMoney();
        FreBalance newFreBalance = new FreBalance();
        newFreBalance.setBalanceId(freBalance.getBalanceId());
        oldMoney=oldMoney.subtract(updateBalanceParam.getUpdateMoney());
        newFreBalance.setBalanceMoney(oldMoney);
        if (freBalanceService.saveOrUpdate(newFreBalance)) {
            return Result.newInstance().setMessage("修改佣金成功").setData(newFreBalance);
        }
        return  Result.newInstance().setMessage("修改佣金失败");
    }


}

